package com.kotiln.lgc.aivoiceapp

import android.Manifest
import android.content.Intent
import android.content.res.TypedArray
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.cardview.widget.CardView
import com.kotiln.lgc.aivoiceapp.data.MainViewPagerListData
import com.kotiln.lgc.aivoiceapp.service.VoiceService
import com.kotiln.lgc.lib_base.adapter.BasePagerAdapter
import com.kotiln.lgc.lib_base.base.BaseActivity
import com.kotiln.lgc.lib_base.event.MessageEvent
import com.kotiln.lgc.lib_base.helper.ARouterHelper
import com.kotiln.lgc.lib_base.util.LogUtil
import com.kotiln.lgc.lib_network.HttpManager
import com.yanzhenjie.permission.Action
import com.zhy.magicviewpager.transformer.ScaleInTransformer
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.ResponseBody
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response


//Ai语音助手(kotlin+组件化)
class MainActivity : BaseActivity() {

    private val mViewPagerList = mutableListOf<MainViewPagerListData>()

    private val mListView = mutableListOf<View>()

    private lateinit var mList: ArrayList<String>

    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }

    override fun getTitleText(): String {
        return getString(R.string.app_name)
    }

    override fun isShowBack(): Boolean {
        return true
    }

    override fun initView() {
        //注册EventBus
        //EventManager.register(this)

        //测试存储数据使用SharedPreferences  TODO 有问题 待处理
        //SpUtil.putString("lgc", "aaa")
        //val key: String? = SpUtil.getString("lgc")
        //key?.let { LogUtil.e(it) }
    }

    override fun initData() {
        //动态权限
        if (checkPermission(Manifest.permission.RECORD_AUDIO)) {
            linkService()
        } else {
            requestPermission(arrayOf(Manifest.permission.RECORD_AUDIO), Action<List<String>> {
                linkService()
            })
        }

        //窗口权限
        if (!checkWindowPermission()) {
            requestWindowPermission(packageName)
        }

        initPagerData()

        initPagerView()


        //测试EventBus
//        btn1.setOnClickListener {
//            EventManager.post(1111)
//        }

        //测试EventBus 传数据
        /*btn2.setOnClickListener {
            EventManager.post(2222, "Hello EventBus")
        }*/

        //测试RecyclerView 模拟数据
        /* mList = ArrayList()
         for (i in 1..30) {
             mList.add("第${i}个数据")
         }
         mRecyclerView.layoutManager = LinearLayoutManager(this)
         mRecyclerView.adapter =
             CommonAdapter(mList, object : CommonAdapter.OnBindDataListener<String> {
                 override fun onBindViewHolder(
                     model: String,
                     viewHolder: CommonViewHolder,
                     type: Int,
                     position: Int
                 ) {
                     viewHolder.setText(R.id.textview, model)
                 }

                 override fun getLayoutId(type: Int): Int {
                     return R.layout.test_item
                 }
             })

        //retrofit网络请求测试
         testWeather()*/
        testWeather()
    }

    //初始化Viewpager DATA
    private fun initPagerData() {
        val title: Array<String> = resources.getStringArray(R.array.MainTitleArray)
        val color: IntArray = resources.getIntArray(R.array.MainColorArray)
        val icon: TypedArray = resources.obtainTypedArray(R.array.MainIconArray)

        //创建数据模型
        for ((index, value) in title.withIndex()) {
            mViewPagerList.add(
                MainViewPagerListData(
                    value,
                    icon.getResourceId(index, 0),
                    color[index]
                )
            )
        }

        //当前屏幕高度
        val windowHeight: Int = windowManager.defaultDisplay.height
        //创建View 模型
        mViewPagerList.forEach {
            //获取当前View
            val view: View = View.inflate(this, R.layout.layout_main_list, null)
            //获取当前布局子view
            val cvMainView = view.findViewById<CardView>(R.id.mCvMainView)
            val ivMainIcon = view.findViewById<ImageView>(R.id.mIvMainIcon)
            val ivMainText = view.findViewById<TextView>(R.id.mTvMainText)
            //设置数据
            cvMainView.setBackgroundColor(it.color)
            ivMainIcon.setBackgroundResource(it.icon)
            ivMainText.setText(it.title)

            //设置当前View显示屏幕所占高度
            cvMainView.layoutParams?.let { lp ->
                lp.height = windowHeight / 5 * 3

            }

            //点击事件
            view.setOnClickListener { _ ->
                when (it.icon) {
                    R.drawable.img_main_weather ->
                        ARouterHelper.startActivity(ARouterHelper.PATH_WEATHER)

                    R.drawable.img_main_joke_icon ->
                        ARouterHelper.startActivity(ARouterHelper.PATH_JOKE)

                    R.drawable.img_main_map_icon ->
                        ARouterHelper.startActivity(ARouterHelper.PATH_MAP)

                    R.drawable.img_main_app_manager ->
                        ARouterHelper.startActivity(ARouterHelper.PATH_APP_MANAGER)

                    R.drawable.img_main_voice_setting ->
                        ARouterHelper.startActivity(ARouterHelper.PATH_VOICE_SETTING)

                    R.drawable.img_main_system_setting ->
                        ARouterHelper.startActivity(ARouterHelper.PATH_SETTING)

                    R.drawable.img_main_developer ->
                        ARouterHelper.startActivity(ARouterHelper.PATH_DEVELOPER)
                }

            }
            mListView.add(view)
        }
    }

    //初始化ViewPager VIEW
    private fun initPagerView() {
        //每个pager之间的间距，就是两张图片之间空白间隙
        mViewPager.pageMargin = 20
        //设置ViewPager缓存数量，这里最好指定数量跟数据源一样，不然会出现空白
        mViewPager.offscreenPageLimit = mViewPagerList.size
        mViewPager.adapter = BasePagerAdapter(mListView)
        mViewPager.setPageTransformer(true, ScaleInTransformer())
        //mViewPager.setCurrentItem(2,false)
    }


    //连接服务
    private fun linkService() {
        startService(Intent(this, VoiceService::class.java))
    }

    private fun testWeather() {
        HttpManager.queryWeather("北京").enqueue(object : Callback<ResponseBody> {
            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                LogUtil.i("response:${response.body()?.string()}")
            }

            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                LogUtil.i("t:${t.toString()}")
            }

        })
    }


    override fun destoryData() {
        //解绑EventBus
        //EventManager.onRegister(this)
    }

    //EventBus回调
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: MessageEvent?) {
        when (event?.type) {
            1111 -> Toast.makeText(this, event.stringValue, Toast.LENGTH_SHORT).show()
            2222 -> Toast.makeText(this, "2222${event.stringValue}", Toast.LENGTH_SHORT).show()
        }
    }


}